package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        //2.分页查询
        IPage page=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //是否收藏
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //按照时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        page = page(page,lambdaQueryWrapper);
        //3.结果返回
        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 删除素材图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //1.检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.通过id查询素材库有无该素材
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询新闻与该素材是否有关联
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(queryWrapper);
        if (wmNewsMaterials!=null&&wmNewsMaterials.size()!=0){  //返回值为空时，提示素材关联文章无法删除
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文件删除失败，该素材关联了相关的新闻");
        }else {
            //4.删除minio中的图片素材
            String url = wmMaterial.getUrl();
            fileStorageService.delete(url);
            //5.返回值为空，代表无关联新闻--执行删除
            removeById(id);
            //6.返回结果
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    /**
     * 收藏图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectPicture(Integer id) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改数据库
        update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,1));
        //3.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollectPicture(Integer id) {
        //1.检查参数
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改数据库
        update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id).set(WmMaterial::getIsCollection,0));
        //3.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile.getSize() == 0 | multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minio中
        String file = UUID.randomUUID().toString().replace("-","");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = file+ postfix;
        String fileId=null;     //图片存放地址
        try {
            fileId = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            log.info("上传图片到minio中图片的id为，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        //3.保存到数据库中
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);  //url路径
        wmMaterial.setType((short)0);   //0是图片 1是视频
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);   //是否收藏 默认0不收藏
        save(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }
}
